package light.head.framework.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtils {

	private final static String UTF_8 = "UTF-8";

	public static boolean createHtml(HttpServletRequest request, Map<String, Object> parm, String tdp, String tn, String sp) {
		Configuration config = new Configuration();
		config.setLocale(Locale.CHINA);
		config.setDefaultEncoding(UTF_8);
		config.setEncoding(Locale.CHINA, UTF_8);
		config.setServletContextForTemplateLoading(request.getSession().getServletContext(), tdp);
		config.setObjectWrapper(new DefaultObjectWrapper());

		try {
//			String path = request.getSession().getServletContext().getRealPath(sp);
			File file = new File(sp);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), UTF_8));
			Template template = config.getTemplate(tn, UTF_8);
			template.process(parm, out);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (TemplateException e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}
}
